import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// @Author lixiaobin
/// @Date 2024/3/13
/// @Description
class PopRoute extends PopupRoute {
  final Duration _duration = const Duration(milliseconds: 0);
  Widget child;

  PopRoute({required this.child});

  @override
  Color? get barrierColor => null;

  @override
  bool get barrierDismissible => true;

  @override
  String? get barrierLabel => null;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
    return child;
  }

  @override
  Duration get transitionDuration => _duration;
}

class WidgetModel {
  final Widget widget;
  final Size size;

  WidgetModel(this.widget, this.size);
}

class Popup extends StatelessWidget {
  final List<WidgetModel> children;
  final GlobalKey globalKey;
  EdgeInsetsGeometry margin;

  double anchorLeft = 0;
  double anchorTop = 0;
  Size anchorSize = Size.zero;

  Popup({super.key, required this.children, required this.globalKey, this.margin = EdgeInsets.zero}) {
    final RenderBox? renderBox = globalKey.currentContext?.findRenderObject() as RenderBox?;
    var underOffset = renderBox?.localToGlobal(Offset(0.0, renderBox.size.height));
    anchorLeft = underOffset?.dx ?? 0;
    anchorTop = underOffset?.dy ?? 0;
    anchorSize = renderBox?.size ?? Size.zero;
  }

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    return Material(
      color: Colors.transparent,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Stack(children: [
          Container(
            width: width,
            height: MediaQuery.of(context).size.height,
            color: Colors.transparent,
          ),
          ...(children.mapIndexed<Widget>((i, e) {
            var left = anchorLeft + (anchorSize.width / 2) - (e.size.width / 2) + margin.horizontal;
            if (left + e.size.width > width) {
              left = width - e.size.width - 5.w;
            }
            double tempTop = 0;
            for (var j = 0; j < children.length; j++) {
              if (j >= i) break;
              tempTop += children[j].size.height;
            }
            var top = (anchorTop + tempTop - 1.w) + margin.vertical;
            return Positioned(
              left: left,
              top: top,
              child: GestureDetector(
                  child: e.widget,
                  onTap: () {
                    Navigator.of(context).pop();
                  }),
            );
          }).toList())
        ]),
        onTap: () {
          //点击空白处
          Navigator.of(context).pop();
        },
      ),
    );
  }
}
